package com.itjeffrey.autocode.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * CORS解决跨域问题
 *
 * @From: Jeffrey
 * @Date: 2020/11/13
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {  //CorsFilter一定要注意导入springframework包下的
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //添加允许的域，不要写*,否则Cookie就无法使用了
        config.addAllowedOrigin("http://localhost:9000");
        //是否发送Cookie信息
        config.setAllowCredentials(true);
        //允许的请求方式
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("PATCH");
        //允许的头信息
        config.addAllowedHeader("*");
        //有效时长设为1小时,单位秒
        config.setMaxAge(3600L);

        //2.添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter
        return new CorsFilter(configSource);
    }
}
